package com.zntg.pdf;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class PdfUtil {

    /**
     *
     * @param src PDF模板路径
     * @param dest 生成文件路径
     * @param params 参数集。若为图片，key中需包含image，value为图片地址
     * @throws DocumentException
     * @throws IOException
     */
    public static void generatePDF(String src, String dest, Map<String,String> params) throws DocumentException, IOException {

        File file = new File(dest);
        file.getParentFile().mkdirs();
        PdfReader reader =null;
        PdfStamper stamper = null;
        try{
            reader= new PdfReader(src);
            PdfDictionary dict = reader.getPageN(1);
            PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
            if (object instanceof PRStream) {
                PRStream stream = (PRStream)object;
                byte[] data = PdfReader.getStreamBytes(stream);
                stream.setData(new String(data).replace("Hello", "HELLO WORLD").getBytes());
            }
            stamper = new PdfStamper(reader, new FileOutputStream(dest));
            AcroFields form = stamper.getAcroFields();
            for (String key :form.getFields().keySet()){
                if (params.get(key)!=null){
                    //根据表单域名区分类型
                    if (!key.startsWith("Image")){
                        //设置文本域参数值
                        form.setField(key,params.get(key));
                    }else{
                        //将图片写入指定的field
                        Image image = Image.getInstance(params.get(key));
                        PushbuttonField pb = form.getNewPushbuttonFromField(key);
                        pb.setImage(image);
                        form.replacePushbuttonField(key, pb.getField());
                    }
                }
            }
            stamper.setFormFlattening(true);
        }finally {
            try{
                if (stamper!=null){
                    stamper.close();
                }
            }catch (Exception e){
            }
            try{
                if (reader!=null){
                    reader.close();
                }
            }catch (Exception e){
            }
        }
    }
    public static void main(String args[]){
        try {
            Map<String,String> params =new HashMap<String, String>();
            generatePDF("D:\\work\\ylcaifu\\智能投顾二期\\pdf\\hello.pdf","D:\\work\\ylcaifu\\智能投顾二期\\pdf\\create\\1.pdf",params);
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}